package tn.orange.canreminder;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import tn.orange.canreminder.adapter.EquipeAdapter;
import tn.orange.canreminder.facebook.BaseDialogListener;
import tn.orange.canreminder.facebook.BaseRequestListener;
import tn.orange.canreminder.facebook.LoginButton;
import tn.orange.canreminder.facebook.SessionEvents.AuthListener;
import tn.orange.canreminder.facebook.SessionEvents.LogoutListener;
import tn.orange.canreminder.facebook.SessionStore;
import tn.orange.canreminder.helper.CalendrierHelper;
import tn.orange.canreminder.model.Country;
import tn.orange.canreminder.singleton.CountrySingleton;
import tn.orange.canreminder.sqlite.Equipe;
import tn.orange.canreminder.sqlite.EquipeDao;
import tn.orange.canreminder.sqlite.EquipeDaoImp;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;

public class ListEquipeActivity extends Activity {

	private List<Country> countries;
	private ListView listView;
	public static final String APP_ID = "277789552279694";

	private Facebook mFacebook;
	private AsyncFacebookRunner mAsyncRunner;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.equipes);
		listView = (ListView) findViewById(R.id.list_equipes);
		EquipeAsyncTask asyncTask = new EquipeAsyncTask();
		asyncTask.execute();
	}

	public void OnFBClick(View V) {
		try {
			Facebook mFacebook = new Facebook("277789552279694");
			mAsyncRunner = new AsyncFacebookRunner(mFacebook);

			SessionStore.restore(mFacebook, this);

			LoginButton button = (LoginButton) V;
			Country country = (Country) V.getTag();
			button.init(this, mFacebook);

			if (APP_ID == null) {
				Util.showAlert(
						this,
						"Warning",
						"Facebook Applicaton ID must be "
								+ "specified before running this example: see Example.java");
			}

			Bundle params = new Bundle();
			params.putString("caption",
					" Vivez le CAN 2012 avec CANReminder ;)");
			params.putString("description", "Suivez la " + country.getName()
					+ " lors de la Coupe d'Afrique des Nations 2012 ici ! ");
			String HACK_ICON_URL = "http://www.kawarji.com/upl/news/logo_can_2012_01.jpg";
			params.putString("picture", HACK_ICON_URL);

			mFacebook.dialog(ListEquipeActivity.this, "feed", params,
					new SampleDialogListener());

		} catch (Exception e) {
			// TODO: handle exception
			showErrorDialog("problème de connexion");
		}

	}

	public void OnConfigClick(final View V) {
		// TODO Auto-generated method stub
		LayoutInflater factory = LayoutInflater.from(ListEquipeActivity.this);
		final View alertDialogView = factory.inflate(R.layout.equipe_config,
				null);

		// Création de l'AlertDialog
		AlertDialog.Builder adb = new AlertDialog.Builder(
				ListEquipeActivity.this);

		// On affecte la vue personnalisé que l'on a crée à notre
		// AlertDialog
		adb.setView(alertDialogView);

		// On donne un titre à l'AlertDialog
		adb.setTitle("Recevoir une notification");

		// On modifie l'icône de l'AlertDialog pour le fun ;)
		adb.setIcon(android.R.drawable.ic_dialog_alert);
		final Spinner s = (Spinner) alertDialogView.findViewById(R.id.spinner);

		ArrayAdapter adapter = ArrayAdapter.createFromResource(
				ListEquipeActivity.this, R.array.notif,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		s.setAdapter(adapter);

		adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

				int pos = (Integer) V.getTag();

				try {

					Country country = countries.get(pos);
					String[] args = new String[] { country.getName(),
							s.getSelectedItem().toString() };
					CalendarAsyncTask asyncTask = new CalendarAsyncTask();
					asyncTask.execute(args);

					// holder.alarm.setText("Alarme : "
					// + CalendrierHelper
					// .getSelectedTime("" + min));
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

		});

		// On crée un bouton "Annuler" à notre AlertDialog et on lui
		// affecte un évènement
		adb.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				// Lorsque l'on cliquera sur annuler on
				// quittera l'application

			}
		});
		adb.show();

	}

	public void OpenCalendar(View V) {

		Intent calendarIntent = new Intent();
		calendarIntent.setClassName("com.android.calendar",
				"com.android.calendar.AgendaActivity");

		startActivity(calendarIntent);
	}

	private class EquipeAsyncTask extends AsyncTask<Void, Void, List<Country>> {
		private final ProgressDialog dialog = new ProgressDialog(
				ListEquipeActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected List<Country> doInBackground(final Void... args) {

			List<Country> countries = null;

			try {

				// categories = service.getAllCategories(nameValuePairs);
				countries = CountrySingleton.getInstance();
				if (countries.size() == 0)
					throw new NullPointerException();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(false);
			}
			return countries;
		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}

		}

		// can use UI thread here
		protected void onPostExecute(final List<Country> countries1) {
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
				countries = countries1;

				listView.setAdapter(new EquipeAdapter(ListEquipeActivity.this,
						countries1));

			}

		}

	}

	private class CalendarAsyncTask extends AsyncTask<String, Void, Void> {
		private final ProgressDialog dialog = new ProgressDialog(
				ListEquipeActivity.this);

		// can use UI thread here
		protected void onPreExecute() {
			this.dialog.setMessage("Veuillez patienter...");
			this.dialog.setCancelable(false);
			this.dialog.show();
		}

		// automatically done on worker thread (separate from UI thread)
		protected Void doInBackground(final String... args) {
			int min = CalendrierHelper.convertTominutes(args[1]);

			try {
				CalendrierHelper.saveIntoCalenndar(args[0],
						ListEquipeActivity.this, min);
				EquipeDao equipeDaoImp = new EquipeDaoImp(
						ListEquipeActivity.this);
				Equipe equipe = new Equipe();
				equipe.setNom(args[0]);
				equipe.setType("" + min);
				equipeDaoImp.insertOrUpdateEquipe(equipe);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				cancel(false);
			}

			return null;

		}

		@Override
		protected void onCancelled() {
			// TODO Auto-generated method stub
			super.onCancelled();
			if (this.dialog.isShowing()) {
				this.dialog.dismiss();
			}
			showErrorDialog("Problème de connexion ");

		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			EquipeAsyncTask asyncTask2 = new EquipeAsyncTask();
			asyncTask2.execute();

			if (this.dialog.isShowing()) {
				this.dialog.dismiss();

			}

		}

		private void showErrorDialog(String message) {
			AlertDialog alertDialog = new AlertDialog.Builder(
					ListEquipeActivity.this).create();
			alertDialog.setTitle("Erreur");
			alertDialog.setMessage(message);
			alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {

				}
			});

			alertDialog.show();
		}

	}

	public class SampleAuthListener implements AuthListener {

		public void onAuthSucceed() {

		}

		public void onAuthFail(String error) {

		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		try {
			mFacebook.authorizeCallback(requestCode, resultCode, data);
		} catch (Exception e) {
			showErrorDialog("Problème de connexion");
		}

	}

	public class SampleLogoutListener implements LogoutListener {
		public void onLogoutBegin() {

		}

		public void onLogoutFinish() {

		}
	}

	public class SampleRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				// process the response here: executed in background thread
				Log.d("Facebook-Example", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				final String name = json.getString("name");

				// then post the processed result back to the UI thread
				// if we do not do this, an runtime exception will be generated
				// e.g. "CalledFromWrongThreadException: Only the original
				// thread that created a view hierarchy can touch its views."
				ListEquipeActivity.this.runOnUiThread(new Runnable() {
					public void run() {

					}
				});
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

	public class SampleUploadListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			try {
				// process the response here: (executed in background thread)
				Log.d("Facebook-Example", "Response: " + response.toString());
				JSONObject json = Util.parseJson(response);
				final String src = json.getString("src");

				// then post the processed result back to the UI thread
				// if we do not do this, an runtime exception will be generated
				// e.g. "CalledFromWrongThreadException: Only the original
				// thread that created a view hierarchy can touch its views."
				ListEquipeActivity.this.runOnUiThread(new Runnable() {
					public void run() {

					}
				});
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
		}
	}

	public class WallPostRequestListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			Log.d("Facebook-Example", "Got response: " + response);
			String message = "<empty>";
			try {
				JSONObject json = Util.parseJson(response);
				message = json.getString("message");
			} catch (JSONException e) {
				Log.w("Facebook-Example", "JSON Error in response");
			} catch (FacebookError e) {
				Log.w("Facebook-Example", "Facebook Error: " + e.getMessage());
			}
			final String text = "Your Wall Post: " + message;
			ListEquipeActivity.this.runOnUiThread(new Runnable() {
				public void run() {

				}
			});
		}
	}

	public class WallPostDeleteListener extends BaseRequestListener {

		public void onComplete(final String response, final Object state) {
			if (response.equals("true")) {
				Log.d("Facebook-Example", "Successfully deleted wall post");
				ListEquipeActivity.this.runOnUiThread(new Runnable() {
					public void run() {

					}
				});
			} else {
				Log.d("Facebook-Example", "Could not delete wall post");
			}
		}
	}

	public class SampleDialogListener extends BaseDialogListener {

		public void onComplete(Bundle values) {
			final String postId = values.getString("post_id");
			if (postId != null) {
				Log.d("Facebook-Example", "Dialog Success! post_id=" + postId);
				mAsyncRunner.request(postId, new WallPostRequestListener());

			} else {
				Log.d("Facebook-Example", "No wall post made");
			}
		}
	}

	public void OnHomeClick(View v) {
		Intent intent = new Intent(getApplicationContext(),
				DashboardActivity.class);
		startActivity(intent);
	}

	private void showErrorDialog(String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(
				ListEquipeActivity.this).create();
		alertDialog.setTitle("Erreur");
		alertDialog.setMessage(message);
		alertDialog.setButton("Ok", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {

			}
		});

		alertDialog.show();
	}

}
